package ude.univ.esiag.gon.uchiha.subscriber.impl;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Vector;

import ude.univ.esiag.gon.uchiha.operation.Operation;
import ude.univ.esiag.gon.uchiha.subscriber.DataReactor;
import ude.univ.esiag.gon.uchiha.subscriber.Semaphore;
import ude.univ.esiag.gon.uchiha.subscriber.Subscriber;

public class SubscriberImpl implements Subscriber{
	private DataReactor reactor;
	private HashMap<String, Vector<Operation>> opMap;
	private Semaphore semaphore;
	public SubscriberImpl(DataReactor reactor) {
		this.reactor = reactor;
		opMap = new HashMap<String, Vector<Operation>>();
		semaphore = new Semaphore();
	}
	public void publish(Serializable obj) throws RemoteException {
		addOperation((Operation)obj);
		reactor.signal(obj);
	}
	synchronized public void addOperation(Operation op){
		semaphore.stop();
		Vector<Operation> ops = opMap.get(op.getData().getTopicName());
		if(ops == null){
			ops = new Vector<Operation>();
			opMap.put(op.getData().getTopicName(), ops);
		}
		ops.add(op);
		semaphore.signal();
	}
	synchronized public Operation read(String topicName){
		semaphore.stop();
		Operation op = null;
		Vector<Operation> ops = opMap.get(topicName);
		if(ops != null && ops.size() > 0){
			op = ops.remove(0);
		}
		semaphore.signal();
		return op;
	}
}
